package com.hundsun.cprs.yyt.web.action.order;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.Assert;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSON;
import com.hundsun.cprs.yyt.common.enums.EnumAreaCode;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.dilivery.domain.Delivery;
import com.hundsun.cprs.yyt.service.dilivery.domain.DeliveryCompany;
import com.hundsun.cprs.yyt.service.dilivery.domain.DeliveryLog;
import com.hundsun.cprs.yyt.service.dilivery.domain.DiliveryAddress;
import com.hundsun.cprs.yyt.service.dilivery.domain.query.DeliveryLogQuery;
import com.hundsun.cprs.yyt.service.dilivery.enums.EnumDiliveryType;
import com.hundsun.cprs.yyt.service.dilivery.service.DeliveryCompanyService;
import com.hundsun.cprs.yyt.service.dilivery.service.DeliveryLogService;
import com.hundsun.cprs.yyt.service.dilivery.service.DeliveryService;
import com.hundsun.cprs.yyt.service.dilivery.service.DiliveryAddressService;
import com.hundsun.cprs.yyt.service.goods.domain.GoodsSpecs;
import com.hundsun.cprs.yyt.service.goods.service.GoodsSkuService;
import com.hundsun.cprs.yyt.service.order.domain.query.OrderInfoQuery;
import com.hundsun.cprs.yyt.service.order.dto.OrderInfo;
import com.hundsun.cprs.yyt.service.order.enums.EnumDeliveryMethod;
import com.hundsun.cprs.yyt.service.order.enums.EnumsOrderStatus;
import com.hundsun.cprs.yyt.service.order.service.OrderService;
import com.hundsun.cprs.yyt.util.DateUtil;
import com.hundsun.cprs.yyt.util.ExportExcelUtil;
import com.hundsun.cprs.yyt.util.excel.EasyExcelUtil;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.cprs.yyt.web.util.ExportExcelWrapper;
import com.hundsun.cprs.yyt.web.vo.JsonModel;
import com.hundsun.cprs.yyt.web.vo.excel.OrderDeliveryExcelVo;
import com.hundsun.cprs.yyt.web.vo.excel.OrderInfoVo;


@Controller
@RequestMapping("/order")
public class OrderAction extends BaseAction {

    @Autowired
    private OrderService orderService;
    @Autowired
    private DeliveryService deliveryService;
    @Autowired
    private DiliveryAddressService diliveryAddressService;
    @Autowired
    private GoodsSkuService skuService;
    @Autowired
    private DeliveryCompanyService deliveryCompanyService;
    @Autowired
    private DeliveryLogService deliveryLogService;

    @RequestMapping("/list")
    public void list(@ModelAttribute("query") OrderInfoQuery query, ModelMap model) {
        publishTimeChans(query);
        orderService.selectOrderInfoByPage(query);
        model.put("orderStatusMap", EnumsOrderStatus.toMap());
    }

    @RequestMapping("/list/{code}")
    public String list(@PathVariable("code") String code, @ModelAttribute("query") OrderInfoQuery query, ModelMap model) {
        EnumsOrderStatus status = EnumsOrderStatus.indexByCode(code);
        if (status == null) {
            return error(model, "页面不存在");
        }
        publishTimeChans(query);
        query.setStatus(status.getStatus());
        orderService.selectOrderInfoByPage(query);
        model.put("orderStatusMap", EnumsOrderStatus.toMap());
        model.put("statusCode", code);
        model.put("statusValue", status.getStatus());
        return "/order/list";
    }

    @RequestMapping("/listWholesale")
    public void listWholesale(@ModelAttribute("query") OrderInfoQuery query, ModelMap modelMap) {
        query.setAreaCode(EnumAreaCode.WHOLESALE_AREA.getCode());
        publishTimeChans(query);
        orderService.selectOrderInfoByPage(query);
        modelMap.put("orderStatusMap", EnumsOrderStatus.toMap());
    }

    @RequestMapping("/listRetail")
    public void listRetail(@ModelAttribute("query") OrderInfoQuery query, ModelMap modelMap) {
        query.setAreaCode(EnumAreaCode.RETAIL_AREA.getCode());
        publishTimeChans(query);
        orderService.selectOrderInfoByPage(query);
        modelMap.put("orderStatusMap", EnumsOrderStatus.toMap());
    }

    @RequestMapping("/view")
    public void view(@RequestParam("orderId") Long orderId, ModelMap model) {
        OrderInfo orderInfo = orderService.selectOrderInfoById(orderId);
        GoodsSpecs sku = skuService.selectByPrimaryKey(orderInfo.getOrderItems().get(0).getSkuId());
        if (sku != null) {
            model.addAttribute("returnMoney", sku.getGoodsPrice() * orderInfo.getOrderItems().get(0).getReturnedQuantity());
        }
        model.addAttribute("data", orderInfo);
        model.put("orderStatusMap", EnumsOrderStatus.toMap());
        model.put("EnumAreaCodeMap", EnumAreaCode.toMap());
        model.put("EnumDiliveryTypeMap", EnumDiliveryType.toMap());
    }

    @RequestMapping(value = "/doDilivery", method = RequestMethod.GET)
    public void doDilivery(@RequestParam("orderId") Long orderId, ModelMap model) {
        OrderInfo orderInfo = orderService.selectOrderInfoById(orderId);
        model.addAttribute("data", orderInfo);
        model.put("orderStatusMap", EnumsOrderStatus.toMap());
        model.put("EnumAreaCodeMap", EnumAreaCode.toMap());
        model.put("EnumDiliveryTypeMap", EnumDiliveryType.toMap());
        model.put("EnumDeliveryCompany", deliveryCompanyService.queryCompanyList());
        if (orderInfo.getDeliveryType() == EnumDeliveryMethod.SELFGET.ordinal()) {
            //获取自提地址信息
            DiliveryAddress address = diliveryAddressService.selectAddressDetailByAddressId(orderInfo.getDiliveryId());
            model.addAttribute("selfGetAddress", address.getDiliveryAddress());
            //计算自提数量
            model.addAttribute("selfGetAmount", orderInfo.getOrderItems().get(0).getQuantity() - orderInfo.getOrderItems().get(0).getShippedQuantity());
        }
    }

    @RequestMapping(value = "/doDilivery", method = RequestMethod.POST)
    public String doDilivery(Delivery dilivery, ModelMap model) {
        OrderInfo orderInfo = orderService.selectOrderInfoById(dilivery.getOrderId());
        if (orderInfo != null) {
            try {
                if (orderInfo.getDeliveryType() == EnumDeliveryMethod.DELIVERY.ordinal()) {
                    Assert.notNull(dilivery.getCompanyCode(), "物流公司不能为空");
                    Assert.notNull(dilivery.getBatchNumber(), "物流编号不能为空");
                    //根据物流公司编号查找物流公司名称
                    DeliveryCompany deliveryCompany = deliveryCompanyService.selectCompanyByCode(dilivery.getCompanyCode());
                    if (deliveryCompany == null) {
                        throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1524.getErrorNo(), EnumBusinessCode.BUSINESS_1524.getErrorInfo());
                    }
                    dilivery.setLogisticsCompany(deliveryCompany.getLogisticsCompany());
                } else {
                    dilivery.setCompanyCode(BigDecimal.ZERO.toString());
                }
                dilivery.setAddress(orderInfo.getAddress());
                dilivery.setContactNumber(orderInfo.getPhone());
                dilivery.setUserName(orderInfo.getConsignee());
                deliveryService.createDelivery(dilivery);
                if (orderInfo.getAreaCode().equals(EnumAreaCode.RETAIL_AREA.getCode())) {
                    return success(model, "发货成功", "/order/listRetail");
                } else {
                    return success(model, "发货成功", "/order/listWholesale");
                }
            } catch (ServiceCodeException e) {
                if (orderInfo.getAreaCode().equals(EnumAreaCode.RETAIL_AREA.getCode())) {
                    return error(model, e.getErrorDesc(), "/order/listRetail");
                } else {
                    return error(model, e.getErrorDesc(), "/order/listWholesale");
                }
            }
        } else {
            return error(model, "发货失败，订单不存在");
        }
    }

    @RequestMapping(value = "batch_delivery")
    public void batchDelivery(@ModelAttribute("query") DeliveryLogQuery query, ModelMap model) {
        deliveryLogService.queryByPage(query);

        List<DeliveryCompany> companysList = deliveryCompanyService.queryCompanyList();
        if (CollectionUtils.isNotEmpty(companysList)) {
            List<String> companyName = new ArrayList<String>(companysList.size());
            for (DeliveryCompany temp : companysList) {
                companyName.add(temp.getLogisticsCompany());
            }
            model.put("companyMemo", StringUtils.join(companyName.iterator(), ","));
        }
        model.put("deliveryTypeMap", EnumDiliveryType.toMap());
    }

    @RequestMapping(value = "batch_delivery/delete")
    public String deleteBatchDeliveryLog() {
        deliveryLogService.deleteAll();
        return "redirect:/order/batch_delivery.htm";
    }

    @RequestMapping(value = "batch_delivery/import", method = RequestMethod.POST)
    public @ResponseBody
    String batchDelivery(@RequestParam("file") MultipartFile file, HttpServletResponse resposne) {
        List<OrderDeliveryExcelVo> uploadDatas = EasyExcelUtil.readExcel(file, OrderDeliveryExcelVo.class);

        Set<DeliveryLog> datas = new HashSet<DeliveryLog>();
        for (OrderDeliveryExcelVo temp : uploadDatas) {
            if (StringUtils.isEmpty(temp.getOrderNo())) {
                continue;
            }
            DeliveryLog log = new DeliveryLog();
            log.setBatchNumber(temp.getBatchNumber());
            log.setLogisticsCompany(temp.getLogisticsCompany());
            log.setOrderSn(temp.getOrderNo());
            datas.add(log);
        }

        if (datas.size() > 0) {
            deliveryLogService.batchInsert(new ArrayList<>(datas));
        }

        //自动触发处理
        deliveryLogService.handleBatchDelivery();

        Map<String, Object> importStatInfo = new HashMap<String, Object>();
        importStatInfo.put("total", uploadDatas.size());
        importStatInfo.put("uniqueTotal", datas.size());

        JsonModel result = new JsonModel(JsonModel.RESULD_CODE_SUCCESS, "success", importStatInfo);
        return JSON.toJSONString(result);
    }

    public void publishTimeChans(OrderInfoQuery query) {
        if (query.getStartDate() == null) {
            query.setStartDate(DateUtil.getBeginOfDay(new Date()));
        }
        if (query.getEndDate() == null) {
            query.setEndDate(DateUtil.getEndOfDay(new Date()));
        }
    }

    @RequestMapping("/export/excel")
    public void exportExcel(OrderInfoQuery query, HttpServletRequest request, HttpServletResponse response) throws Exception {
        query.setPageSize(30000);
        publishTimeChans(query);
        orderService.selectOrderInfoByPageExt(query);

        List<OrderInfoVo> exportResult = new ArrayList<OrderInfoVo>();
        for (OrderInfo item : query.getData()) {
            exportResult.add(new OrderInfoVo(item));
        }
        String[] columnNames = {"订单编号", "商品名称", "商品编号", "订单总金额(元)", "买家交易账号", "买家姓名", "订单状态", "下单时间", "支付时间", "交割类型", "发货数量", "收货人", "联系电话", "收货地址"};
        String fileName = "订单数据导出";
        ExportExcelWrapper<OrderInfoVo> util = new ExportExcelWrapper<OrderInfoVo>();
        util.exportExcel(fileName, fileName, columnNames, exportResult, response, ExportExcelUtil.EXCEl_FILE_2007);
    }

    @Override
    protected void initBinder(WebDataBinder binder) {
        // 注册默认的日期格式化类型: yyyy-MM-dd
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

    @RequestMapping("delete.json")
    @ResponseBody
    public JsonModel delete(Long orderId) {
        try {
            orderService.delete(orderId);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS, "删除成功");
        } catch (Exception e) {
            log.error("订单删除异常:", e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL, e.getMessage());
        }
    }
}
